﻿using AutoMapper;
using MediatR;
using RearLivestock.Common.Domains.hhx;
using RearLivestock.Common.Domains.wbx;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.RBAC.Api.hhxApplication.Commands.User
{
    public class AddUserHandler : IRequestHandler<AddUserCommand, Result>
    {
        private readonly IMapper mapper;
        private readonly IBaseRepository<Users> usersRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="usersRepository"></param>
        public AddUserHandler(IMapper mapper, IBaseRepository<Users> usersRepository)
        {
            this.mapper = mapper;
            this.usersRepository = usersRepository;
        }

        /// <summary>
        /// 用户信息添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(AddUserCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                Users user = mapper.Map<Users>(request);
                var res = await usersRepository.Add(user);
                if (res > 0)
                { 
                    result.Code = (int)CommonErrorCode.Success;
                }
                result.Msg = "用户添加成功";
            }
            catch (Exception)
            {
                result.Msg = "用户信息添加异常";
            }
            return result;
        }
    }
}
